import 'package:mysql1/mysql1.dart';
import '../models/user.dart';

class DatabaseService {
  static MySqlConnection? _connection;
  static const String _host = 'localhost';
  static const int _port = 3306;
  static const String _dbName = 'accept';
  static const String _username = 'root';
  static const String _password = 'root';

  static Future<MySqlConnection> get connection async {
    if (_connection == null) {
      try {
        print('正在连接数据库...');
        final settings = ConnectionSettings(
          host: _host,
          port: _port,
          db: _dbName,
          user: _username,
          password: _password,
        );
        print('连接参数: host=${settings.host}, port=${settings.port}, db=${settings.db}, user=${settings.user}');
        _connection = await MySqlConnection.connect(settings);
        print('数据库连接成功');
        return _connection!;
      } catch (e) {
        print('数据库连接失败: $e');
        rethrow;
      }
    }
    return _connection!;
  }

  static Future<User?> authenticateUser(String username, String password) async {
    print('开始验证用户: $username');
    try {
      final conn = await connection;
      print('数据库连接成功');

      final results = await conn.query(
        'SELECT * FROM users WHERE username = ? AND password = ?',
        [username, password],
      );
      print('查询结果: ${results.length} 条记录');

      if (results.isNotEmpty) {
        final row = results.first;
        print('用户数据: $row');
        print('用户名称字段类型: ${row['real_name'].runtimeType}');
        print('用户名称值: ${row['real_name']}');
        print('用户名称是否为空: ${row['real_name'] == null}');

        try {
          final user = User.fromMap({
            'id': row['id'],
            'username': row['username'],
            'name': row['real_name'] ?? '未命名用户',
            'email': row['email'],
            'role': row['role'] ?? 'user',
            'last_login_time': row['last_login_time']?.toString(),
          });
          print('用户对象创建成功: ${user.username}, 名称: ${user.name}');
          return user;
        } catch (e) {
          print('创建用户对象时发生错误: $e');
          print('原始数据: $row');
          return null;
        }
      }
      print('未找到匹配的用户');
      return null;
    } catch (e) {
      print('验证用户时发生错误: $e');
      return null;
    }
  }

  static Future<void> updateLastLoginTime(int userId) async {
    try {
      final conn = await connection;
      await conn.query(
        'UPDATE users SET last_login_time = NOW() WHERE id = ?',
        [userId],
      );
    } catch (e) {
      print('更新最后登录时间时发生错误: $e');
    }
  }

  static Future<void> closeConnection() async {
    try {
      if (_connection != null) {
        await _connection!.close();
        _connection = null;
        print('数据库连接已关闭');
      }
    } catch (e) {
      print('关闭数据库连接时发生错误: $e');
    }
  }
} 